//
//  SoundController.m
//  标题按钮
//
//  Created by 李贤立 on 16/5/23.
//  Copyright © 2016年 李贤立. All rights reserved.
//

#import "SoundController.h"
#import "UIImage+Enlarge.h"
#import <Masonry.h>
#import "SoundTools.h"
@interface SoundController ()<SoundToolsDelegate,AVAudioPlayerDelegate>
@property(nonatomic, strong) SoundTools *recordView;

@property(nonatomic, strong) AVAudioPlayer *player;
/**
 *  声音的按钮
 */
@property(nonatomic,strong) UIButton *soundBtn;
/**
 *  获得录音文件的路径
 */
@property(nonatomic, copy) NSString *recordPath;
/**
 *  获得语音文件的长度
 */
@property(nonatomic,assign) CGFloat recordLength;
/**
 *  定时器
 */
@property(nonatomic,strong) NSTimer *timer;
/**
 *  录音时间计数器
 */
@property(nonatomic, assign) NSInteger timeCount;
/**
 *  录音时长的记录值
 */
@property(nonatomic,assign) NSInteger recordCount;
/**
 *  播放时间计数器
 */
@property(nonatomic, assign) NSInteger playCount;
/**
 *  暂停是的记录值
 */
@property(nonatomic,assign) NSInteger pauseCount;

@end
@implementation SoundController
#pragma mark - SoundToolsDelegate
- (void)recordArcView:(SoundTools *)arcView voiceRecorded:(NSString *)recordPath length:(float)recordLength{
    self.recordPath = recordPath;
    self.recordLength = recordLength;
    [self alertViewWithTItle:@"录音"];
}
#pragma mark - AVAudioPlayerDelegate 代理方法
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{
    [self pause_CTP];
    // 重新设置标题时长
    self.navigationItem.title = self.navigationItem.title = [self dateWithDateCount:self.recordCount];
    self.pauseCount = self.recordCount;
}
#pragma mark - 生命周期方法
- (void)viewDidLoad {
    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage loadAnOldImageName:@"CTPNav"]];
    // 设置导航栏
    [self setupNavigationItem];
    // 设置主界面
    [self setupView];
}
/**
 *  私有方法
 *
 *  @param fileName 文件名
 *
 *  @return 存储路径
 */
- (NSString *)fullPathAtCache:(NSString *)fileName{
    NSError *error;
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
    NSFileManager *fm = [NSFileManager defaultManager];
    if (YES != [fm fileExistsAtPath:path]) {
        if (YES != [fm createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:&error]) {
            NSLog(@"create dir path=%@, error=%@", path, error);
        }
    }
    return [path stringByAppendingPathComponent:fileName];
}
/**
 *  私有方法 弹框
 *
 *  @param title 弹框标题
 */
- (void)alertViewWithTItle:(NSString *)title {
    UIAlertController *alert=[UIAlertController alertControllerWithTitle:title message:[NSString stringWithFormat:@"%@地址：%@,  时常：%@",title, self.recordPath, [self dateWithDateCount:self.timeCount]] preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *done=[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alert addAction:done];
    [self presentViewController:alert animated:YES completion:nil];
}
/**
 *  私有方法
 *
 *  字符串时间转换成基本时间格式
 */
- (NSDate *)dateWithDateString:(NSString *)dateString AndDateFormat:(NSString *)dateFormat {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = dateFormat;
    return [formatter dateFromString:dateString];
}
/**
 *  私有方法
 *
 *  字符串时间转换成基本时间格式
 */
- (NSString *)dateWithDateCount:(NSInteger)dateCount {
    NSInteger ss = dateCount % 60;
    NSInteger mm = dateCount / 60;
    NSInteger HH = mm / 60;
    mm = mm - HH * 60;
    return [NSString stringWithFormat:@"%.2zd:%.2zd:%.2zd",HH,mm,ss];
}
/**
 *  私有方法,时间增加
 */
- (void)timeElapse {
    self.timeCount++;
    self.navigationItem.title = [self dateWithDateCount:self.timeCount];
}
/**
 *  私有方法,时间减少
 */
- (void)timeReduce {
    self.playCount--;
    self.navigationItem.title = [self dateWithDateCount:self.playCount];
}
- (void)timePause {
    self.pauseCount--;
    if (self.pauseCount < 0) {
        self.pauseCount = 0;
    }
    self.navigationItem.title = [self dateWithDateCount:self.pauseCount];
}
/**
 *  私有方法,开启定时器
 */
- (void)startTimer1 {
    // 实例化
    self.timer = [NSTimer timerWithTimeInterval:0.01 target:self selector:@selector(timeElapse) userInfo:nil repeats:YES];
    // 获取线程运行环
    NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
    // 添加到线程运行环
    [runLoop addTimer:_timer forMode:NSRunLoopCommonModes];
}
/**
 *  私有方法,开启定时器
 */
- (void)startTimer2 {
    // 实例化
    self.timer = [NSTimer timerWithTimeInterval:0.01 target:self selector:@selector(timeReduce) userInfo:nil repeats:YES];
    // 获取线程运行环
    NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
    // 添加到线程运行环
    [runLoop addTimer:_timer forMode:NSRunLoopCommonModes];
}
/**
 *  私有方法,开启定时器
 */
- (void)startTimer3 {
    // 实例化
    self.timer = [NSTimer timerWithTimeInterval:0.01 target:self selector:@selector(timePause) userInfo:nil repeats:YES];
    // 获取线程运行环
    NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
    // 添加到线程运行环
    [runLoop addTimer:_timer forMode:NSRunLoopCommonModes];
}
- (void)setupNavigationItem {
    self.navigationItem.title = @"00:00:00";
}

- (void)setupView {
    // 指定代理
    self.recordView.delegate = self;
    self.soundBtn.tag = 0;
    // 绑定事件
    [self didClickSoundBtn];
}
// 播放的方法
- (void)didClickSoundBtn {
    switch (self.soundBtn.tag) {
        case 0:// 非点击状态
            [self.soundBtn addTarget:self action:@selector(record_CTP) forControlEvents:UIControlEventTouchUpInside];
            // 设置录音按钮的图片
            [self.soundBtn setImage:[UIImage imageNamed:@"record"] forState:UIControlStateNormal];
            break;
        case 1:// 录音状态
            [self.soundBtn removeTarget:self action:@selector(record_CTP) forControlEvents:UIControlEventTouchUpInside];
            [self.recordView startForFilePath:[self fullPathAtCache:@"record.wav"]];
            // 设置录音停止按钮的图片
            [self.soundBtn setImage:[UIImage imageNamed:@"pause_1"] forState:UIControlStateNormal];
            [self.soundBtn addTarget:self action:@selector(recordPause_CTP) forControlEvents:UIControlEventTouchUpInside];
            break;
        case 2:// 录音停止状态
            [self.soundBtn removeTarget:self action:@selector(recordPause_CTP) forControlEvents:UIControlEventTouchUpInside];
            [self.recordView commitRecording];
            // 设置播放按钮的图片
            [self.soundBtn setImage:[UIImage imageNamed:@"play"] forState:UIControlStateNormal];
            [self.soundBtn addTarget:self action:@selector(play_CTP) forControlEvents:UIControlEventTouchUpInside];
            break;
        case 3:// 播放状态
            [self.soundBtn removeTarget:self action:@selector(play_CTP) forControlEvents:UIControlEventTouchUpInside];
            [self.player play];
            // 设置播放按钮的图片
            [self.soundBtn setImage:[UIImage imageNamed:@"pause_2"] forState:UIControlStateNormal];
            [self.soundBtn addTarget:self action:@selector(pause_CTP) forControlEvents:UIControlEventTouchUpInside];
            break;
        case 4:// 播放暂停状态
            [self.soundBtn removeTarget:self action:@selector(pause_CTP) forControlEvents:UIControlEventTouchUpInside];
            [self.player pause];
            // 设置播放暂停的图片
            [self.soundBtn setImage:[UIImage imageNamed:@"play"] forState:UIControlStateNormal];
            [self.soundBtn addTarget:self action:@selector(resume_CTP) forControlEvents:UIControlEventTouchUpInside];
            break;
        default:
            break;
    }
}
// 开始录音
- (void)record_CTP {
    // 设置标记
    self.soundBtn.tag = 1;
    // 绑定事件
    [self didClickSoundBtn];
    // 开启定时器
    [self startTimer1];
}
// 录音停止
- (void)recordPause_CTP {
    // 设置标记
    self.soundBtn.tag = 2;
    // 绑定事件
    [self didClickSoundBtn];
    // 记录录音时长
    self.recordCount = self.timeCount;
    // 获得播放时长计数器最大值
    self.playCount = self.recordCount;
    // 销毁定时器
    [self.timer invalidate];
}
// 开始播放
- (void)play_CTP {
    [self alertViewWithTItle:@"播放"];
    // 设置标记
    self.soundBtn.tag = 3;
    // 绑定事件
    [self didClickSoundBtn];
    // 开启定时器
    [self startTimer2];
}
// 播放暂停
- (void)pause_CTP {
    // 设置标记
    self.soundBtn.tag = 4;
    // 获得播放暂停时长计数器
    if (!self.pauseCount) {
        self.pauseCount = self.playCount;
    }
    // 绑定事件
    [self didClickSoundBtn];
    // 销毁定时器
    [self.timer invalidate];
}
// 继续播放
- (void)resume_CTP {
    // 设置标记
    self.soundBtn.tag = 3;
    // 绑定事件
    [self didClickSoundBtn];
    // 开启计时器
    [self startTimer3];
}
#pragma mark - 懒加载
- (SoundTools *)recordView {
    if (_recordView == nil) {
        _recordView = [[SoundTools alloc] init];
        [self.view addSubview:_recordView];
        _recordView.frame = self.view.bounds;
    }
    return _recordView;
}
- (UIButton *)soundBtn {
    if (_soundBtn == nil) {
        _soundBtn = [[UIButton alloc] init];
        [self.view addSubview:_soundBtn];
        [_soundBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self.view);
            make.centerY.equalTo(self.view).offset([UIScreen mainScreen].bounds.size.height * 0.2);
            make.height.width.mas_equalTo([UIScreen mainScreen].bounds.size.height * 0.3);
        }];
    }
    return _soundBtn;
}
- (AVAudioPlayer *)player {
    if (_player == nil) {
        _player = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:[self fullPathAtCache:@"record.wav"]] error:nil];
        _player.delegate = self;
    }
    return _player;
}
@end
